package com.example.houseitemmanagebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.houseitemmanagebackend.entity.UserSetting;
import com.example.houseitemmanagebackend.mapper.UserSettingMapper;
import com.example.houseitemmanagebackend.service.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 设置服务实现类
 */
@Service
public class SettingServiceImpl implements SettingService {

    @Autowired
    private UserSettingMapper userSettingMapper;

    @Override
    @Cacheable(value = "userSetting", key = "#userId")
    public UserSetting getUserSetting(Integer userId) {
        // 查询用户设置
        LambdaQueryWrapper<UserSetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserSetting::getUserId, userId);
        UserSetting setting = userSettingMapper.selectOne(queryWrapper);

        // 如果不存在，创建默认设置
        if (setting == null) {
            setting = createDefaultSetting(userId);
        }

        return setting;
    }

    @Override
    @Transactional
    @CacheEvict(value = "userSetting", key = "#userId")
    public void updateUserSetting(UserSetting setting, Integer userId) {
        // 查询用户设置
        LambdaQueryWrapper<UserSetting> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserSetting::getUserId, userId);
        UserSetting existingSetting = userSettingMapper.selectOne(queryWrapper);

        if (existingSetting == null) {
            // 不存在则创建
            setting.setUserId(userId);
            setting.setCreatedAt(LocalDateTime.now());
            setting.setUpdatedAt(LocalDateTime.now());
            userSettingMapper.insert(setting);
        } else {
            // 存在则更新
            existingSetting.setLowStockThreshold(setting.getLowStockThreshold());
            existingSetting.setExpiryWarningDays(setting.getExpiryWarningDays());
            existingSetting.setTheme(setting.getTheme());
            existingSetting.setLanguage(setting.getLanguage());
            existingSetting.setUpdatedAt(LocalDateTime.now());
            userSettingMapper.updateById(existingSetting);
        }
    }

    /**
     * 创建默认用户设置
     * 
     * @param userId 用户ID
     * @return 默认用户设置
     */
    private UserSetting createDefaultSetting(Integer userId) {
        UserSetting setting = new UserSetting();
        setting.setUserId(userId);
        setting.setLowStockThreshold(3);
        setting.setExpiryWarningDays(14);
        setting.setTheme("light");
        setting.setLanguage("zh-CN");
        setting.setCreatedAt(LocalDateTime.now());
        setting.setUpdatedAt(LocalDateTime.now());

        userSettingMapper.insert(setting);
        return setting;
    }
}